using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using Lizk.WebScraper;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using TheTVDB;
using System.Linq;

namespace TVScrapers
{
    public class AnimeTVDBScraper : Scraper
    {
        public static TVDB Instance
        {
            get
            {
                return TVDBScraper.Instance;
            }
        }

        private bool CheckConnection()
        {
            if (Instance.XmlMirrors.Count == 0)
            {
                try
                {
                    Instance.AddDefaultMirrors();
                }
                catch { return false; }
            }
            return true;
        }

        public override ScraperResult[] Search(string search)
        {
            UpdateProgress(new ScraperEventArgs("Connecting to TheTvDB", ScraperEventArgs.ScaperStatus.Connecting));
            List<ScraperResult> results = new List<ScraperResult>();


            if (!CheckConnection())
            {
                UpdateProgress(new ScraperEventArgs("Unable to connect to TheTVDB", ScraperEventArgs.ScaperStatus.Error));
                return new ScraperResult[0];
            }

            UpdateProgress(new ScraperEventArgs("Scraping...", ScraperEventArgs.ScaperStatus.Downloading));

            IList<Series> result = Instance.Search(search);
            ScraperResult[] retVal = new ScraperResult[result.Count];

            for (int i = 0; i < result.Count; i++)
            {
                retVal[i] = new ScraperResult(result[i].ID.ToString());
                retVal[i].Title = result[i].Name;
                retVal[i].Summary = result[i].Overview;

            }

            if (retVal.Length == 1)
            {
                ScraperResult r = GetTitleInfo(retVal[0].ID.ToString());
                if(r != null)
                    ScrapeComplete(r);
                return new ScraperResult[]{r};
            }

            UpdateProgress(new ScraperEventArgs("Search completed!", ScraperEventArgs.ScaperStatus.Done));
            SearchComplete(retVal);
            return retVal;
        }

        public override ScraperResult GetTitleInfo(string id)
        {
            UpdateProgress(new ScraperEventArgs("Connecting to TVDB", ScraperEventArgs.ScaperStatus.Connecting));
            int i;
            if (!CheckConnection() || !Int32.TryParse(id, out i))
            {
                UpdateProgress(new ScraperEventArgs("Unable to connect to TheTVDB", ScraperEventArgs.ScaperStatus.Error));
                return null;
            }

            UpdateProgress(new ScraperEventArgs("Scraping...", ScraperEventArgs.ScaperStatus.Downloading));

            Series s = Instance.GetSeries(i);
            if (s == null)
            {
                UpdateProgress(new ScraperEventArgs("Could not find series!", ScraperEventArgs.ScaperStatus.Error));
                return null;
            }

            ScraperResult sr = new ScraperResult(id);
            sr.Summary = string.IsNullOrEmpty(s.Overview) ? "" : s.Overview;
            sr.Title = s.Name;
            sr.RuntimeInMinutes = s.Runtime;
            sr.Rating = s.Rating;
            sr.ImageUrl = Instance.GetBannerUrl(s.BannerPath); 
            foreach (var item in s.Actors)
            {
                sr.People.Add(new Person("", item) { Job = "Actor" });
            }
            sr.Year = s.FirstAired.Year;
            sr.Genres.AddRange(s.Genres);

            var episodes = from e in s.Episodes
                           orderby e.Season, e.EpisodeNumber
                           select e;

            int episodeNumber = 1;
            foreach (var item in episodes)
            {
                Lizk.WebScraper.Episode ep = new Lizk.WebScraper.Episode(item.Name);
                ep.AirDate = item.FirstAired;
                if(item.EpisodeNumber > 0 && item.Season > 0)
                    ep.EpisodeNumber = episodeNumber++;
                ep.Season = 0;
                ep.Summary = item.Overview == null ? "" : item.Overview;
                ep.Title = item.Name == null ? "Unknown Title" : item.Name;
                sr.Episodes.Add(ep);
            }

            UpdateProgress(new ScraperEventArgs("Scrape completed!", ScraperEventArgs.ScaperStatus.Done));
            ScrapeComplete(sr);
            return sr;
        }



    }
}
